package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Lists;
import com.maiji.cloud.entities.login.Label;
import com.maiji.cloud.entities.login.LabelMiddleMaijiArticle;
import com.maiji.cloud.entities.login.MaijiArticle;
import com.maiji.cloud.entities.login.UploadRecord;
import com.maiji.cloud.mapper.MaijiArticleMapper;
import com.maiji.cloud.request.login.MaijiArticleReqData;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.login.MaijiArticleResData;
import com.maiji.cloud.response.login.UploadImageResData;
import com.maiji.cloud.service.LabelMiddleMaijiArticleService;
import com.maiji.cloud.service.LabelService;
import com.maiji.cloud.service.MaijiArticleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.service.UploadRecordService;
import com.maiji.cloud.utils.BaseService;
import com.maiji.cloud.utils.DetailTextUtil;
import com.maiji.cloud.utils.UUID_MD5;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class MaijiArticleServiceImpl extends ServiceImpl<MaijiArticleMapper, MaijiArticle> implements MaijiArticleService {

    @Autowired
    private LabelService labelService;
    @Autowired
    private LabelMiddleMaijiArticleService labelMiddleMaijiArticleService;
    @Autowired
    private UploadRecordService uploadRecordService;

    @Override
    public BaseDataResDto<List<MaijiArticleResData>> findAllMaijiArticleByLabelId(String labelId) {
        Label label = labelService.selectById(labelId);
        Wrapper<Label> labelWrapper = new EntityWrapper<Label>().eq("source", "麦吉简介")
                .eq("order_no", label.getOrderNo()).ne("list_show", label.getListShow());
        List<Label> labels = labelService.selectList(labelWrapper);
        List<String> maijiArticleIds = labelMiddleMaijiArticleService.selectList(new EntityWrapper<LabelMiddleMaijiArticle>().eq("label_id", labelId))
                .parallelStream().map(LabelMiddleMaijiArticle::getMaijiArticleId).collect(Collectors.toList());
        if (maijiArticleIds.size() == 0) return new BaseDataResDto<>(Status.SUCCESS);
        List<MaijiArticle> maijiArticles = selectBatchIds(maijiArticleIds).parallelStream().sorted().collect(Collectors.toList());
        Wrapper<UploadRecord> recordWrapper = new EntityWrapper<UploadRecord>().in("belong_id", maijiArticleIds).eq("is_main", 1);
        List<UploadRecord> uploadRecords = uploadRecordService.selectList(recordWrapper);
        maijiArticles = BaseService.dealWithOneToOne(maijiArticles, "getUuId", MaijiArticle.class,
                "setImg", uploadRecords, "getBelongId", UploadImageResData.class);
        List<MaijiArticleResData> data = Lists.newArrayList();
        for (int i = 0; i <3; i++) {
            int finalI = i;
            MaijiArticleResData maijiArticleResData = new MaijiArticleResData().setType(finalI);
            if (finalI == 2) {
                data.add(maijiArticleResData.setMaijiArticles(maijiArticles));
                continue;
            }
            Optional<Label> labelOptional = labels.parallelStream().filter(l -> l.getListShow() == finalI).findFirst();
            List<String> maijiArticleIds0 = Lists.newArrayList();
            if (labelOptional.isPresent()) {
                Label label0 = labelOptional.get();
                maijiArticleResData.setTitle(label0.getDesc()).setLabelId(label0.getUuId());
                maijiArticleIds0 = labelMiddleMaijiArticleService.selectList(new EntityWrapper<LabelMiddleMaijiArticle>().eq("label_id", label0.getUuId()))
                        .parallelStream().map(LabelMiddleMaijiArticle::getMaijiArticleId).collect(Collectors.toList());
                maijiArticleResData.setTitle(label0.getDesc());
            }
            List<MaijiArticle> maijiArticles0 = Lists.newArrayList();
            if (maijiArticleIds0.size() > 0) {
                List<String> finalMaijiArticleIds = maijiArticleIds0;
                maijiArticles0 = maijiArticles.parallelStream().filter(ma -> finalMaijiArticleIds.contains(ma.getUuId())).collect(Collectors.toList());
                maijiArticles = maijiArticles.parallelStream().filter(ma -> ! finalMaijiArticleIds.contains(ma.getUuId())).collect(Collectors.toList());
            }
            data.add(maijiArticleResData.setMaijiArticles(maijiArticles0));
        }
        return new BaseDataResDto<List<MaijiArticleResData>>(Status.SUCCESS).setData(data);
    }

    @Override
    public BaseResDto del_updMaijiArticleById(MaijiArticle maijiArticle) {
        if (maijiArticle.getType() == 1) if (deleteById(maijiArticle.getUuId())) return new BaseResDto(Status.SUCCESS);
        if (maijiArticle.getType() == 2) if (updateById(maijiArticle)) return new BaseResDto(Status.SUCCESS);
        return new BaseResDto(Status.ERROR);
    }

    @Override
    public BaseResDto add_updMaijiArticle(MaijiArticleReqData data) throws Exception {
        String maijiArticleId = data.getUuId();
        if (StringUtil.isNotBlank(maijiArticleId)) {
            if (! deleteById(maijiArticleId)) return new BaseResDto(Status.ERROR.setMessage("删除原文章失败"));
            if (! uploadRecordService.updateForSet("belong_id = null", new EntityWrapper<UploadRecord>()
                    .eq("belong_id", maijiArticleId).eq("is_main", 1)))
                return new BaseResDto(Status.ERROR.setMessage("删除原文章相关图片失败"));
        } else maijiArticleId = UUID_MD5.getUUID();
        if (! uploadRecordService.updateById(new UploadRecord().setUuId(data.getImageId()).setBelongId(maijiArticleId).setIsMain(1)))
            return new BaseResDto(Status.ERROR.setMessage("保存文章封面失败"));
        List<UploadRecord> uploadRecords = Lists.newArrayList();
        String content = DetailTextUtil.dealDetailText("maiji-article-images", maijiArticleId, data.getContent(), uploadRecords);
        if (uploadRecords.size() > 0) if (! uploadRecordService.insertBatch(uploadRecords)) return new BaseResDto(Status.ERROR.setMessage("保存文章正文图片失败"));
        MaijiArticle maijiArticle = new MaijiArticle();
        BeanUtils.copyProperties(data, maijiArticle);
        if (! insert(maijiArticle.setContent(content))) return new BaseResDto(Status.ERROR.setMessage("保存文章失败"));
        String finalMaijiArticleId = maijiArticleId;
        List<LabelMiddleMaijiArticle> lmmaList = data.getLabelIds().parallelStream().map(labelId ->
                new LabelMiddleMaijiArticle().setUuId(UUID_MD5.getUUID()).setLabelId(labelId).setMaijiArticleId(finalMaijiArticleId)).collect(Collectors.toList());
        if (! labelMiddleMaijiArticleService.insertBatch(lmmaList)) return new BaseResDto(Status.ERROR.setMessage("保存文章标签关联关系失败"));
        return new BaseResDto(Status.SUCCESS);
    }

}
